package com.naiterui.ehp.bs.doctor.dao.impl;

import com.naiterui.common.repository.page.Page;
import com.naiterui.common.repository.page.PageParamVO;
import com.naiterui.ehp.bp.domain.MessagePushHistory;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;
import com.naiterui.ehp.bs.doctor.dao.IMessagePushHistoryDao;
import com.naiterui.ehp.bs.doctor.repository.IMessagePushHistoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 查看推送历史消息
 *
 * @version 2015年7月17日 下午6:54:06 by chenlin
 * @Description 概述
 */
@Component
public class AdMessagePushHistoryDaoImpl  implements IMessagePushHistoryDao {

    @Autowired
    private IMessagePushHistoryRepository messagePushHistoryRepository;

    @Override
    public void save(MessagePushHistory history) {
        messagePushHistoryRepository.save(history);
    }

    @Override
    public Page<MessagePushHistory> findPagePaList(Long doctorId, int pageNo, int pageSize, Date date) {
        Pageable pageable = new PageParamVO(pageNo, pageSize).getPageable(Sort.by("id").descending());
        org.springframework.data.domain.Page<MessagePushHistory> result = messagePushHistoryRepository.findByDoctorIdAndCreatedAtLessThanEqual(doctorId, date, pageable);
        List<MessagePushHistory> messages = null ;
        if (result != null) {
            messages = result.getContent();
            repalceSerTel(messages);
        }
        return Page.buildPage(pageNo, pageSize, messages, result.getTotalElements());
    }

    @Override
    public MessagePushHistory getLateMessage(Long doctorId) {
        List<MessagePushHistory> list = messagePushHistoryRepository.findTop1ByDoctorIdOrderByIdDesc(doctorId);
        if (list != null && !list.isEmpty()) {
            repalceSerTel(list);
            return list.get(0);
        }
        return null;
    }

    /**
     * 替换历史数据客服电话
     * 临时方案
     * TODO：考虑系统消息不持久化电话号码，变化的可能性比较大
     *
     * @param messages
     */
    private void repalceSerTel(List<MessagePushHistory> messages) {
        String serTel = ConfigUtil.getString("init.server.phone");
        messages.forEach(message -> {
            String content = message.getContent().replace("4009-717-717", serTel);
            message.setContent(content);
        });
    }

}
